import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

class ManHelper {
    constructor() {
        const __filename = fileURLToPath(import.meta.url);
        const __dirname = path.dirname(__filename);
        this.configPath = path.join(__dirname, '../ManTokenConfig.ini');
    }

    /**
     * 添加Man对象到配置文件
     * @param {Object} man - Man对象，包含name和token属性
     * @returns {boolean} - 添加是否成功
     */
    addMan(man) {
        try {
            if (!man || !man.name || !man.token) {
                console.error('Man对象必须包含name和token属性');
                return false;
            }

            let manList = this.getAllMen();

            // 检查是否已存在相同name的Man
            const existingIndex = manList.findIndex(m => m.name === man.name);
            if (existingIndex !== -1) {
                // 更新已存在的Man
                manList[existingIndex] = man;
            } else {
                // 添加新Man
                manList.push(man);
            }

            // 将Man列表转换为INI格式并写入文件
            const iniContent = this._convertToIni(manList);
            fs.writeFileSync(this.configPath, iniContent, 'utf8');
            return true;
        } catch (error) {
            console.error('添加Man失败:', error);
            return false;
        }
    }

    /**
     * 从配置文件读取所有Man对象
     * @returns {Array} - Man对象数组
     */
    getAllMen() {
        try {
            if (!fs.existsSync(this.configPath)) {
                return [];
            }

            const iniContent = fs.readFileSync(this.configPath, 'utf8');
            return this._parseIni(iniContent);
        } catch (error) {
            console.error('读取Man列表失败:', error);
            return [];
        }
    }

    /**
     * 获取配置文件中所有Man的name
     * @returns {Array} - 包含所有name的数组
     */
    getAllNames() {
        const manList = this.getAllMen();
        return manList.map(man => man.name);
    }

    /**
     * 根据name查询对应的token
     * @param {string} name - 要查询的name
     * @returns {string|undefined} - 找到则返回token，否则返回undefined
     */
    getTokenByName(name) {
        const manList = this.getAllMen();
        const man = manList.find(m => m.name === name);
        return man ? man.token : undefined;
    }

    /**
     * 将Man列表转换为INI格式
     * @param {Array} manList - Man对象数组
     * @returns {string} - INI格式的字符串
     * @private
     */
    _convertToIni(manList) {
        let iniContent = '';
        manList.forEach((man, index) => {
            iniContent += `[Man${index + 1}]\n`;
            iniContent += `name=${man.name}\n`;
            iniContent += `token=${man.token}\n\n`;
        });
        return iniContent;
    }

    /**
     * 解析INI格式的内容为Man对象数组
     * @param {string} iniContent - INI格式的字符串
     * @returns {Array} - Man对象数组
     * @private
     */
    _parseIni(iniContent) {
        const manList = [];
        const sections = iniContent.split(/\[\w+\]/g).filter(Boolean);

        sections.forEach(section => {
            const lines = section.trim().split('\n').filter(Boolean);
            const man = {};

            lines.forEach(line => {
                const [key, value] = line.split('=').map(part => part.trim());
                if (key && value) {
                    man[key] = value;
                }
            });

            if (man.name && man.token) {
                manList.push(man);
            }
        });

        return manList;
    }
}

let manHelper = new ManHelper();
export default manHelper;